import { Component } from "@angular/core";
import { ModalController, ToastController } from "@ionic/angular";
import { Global } from "src/app/services/global.service";
import { TemplateItemConfig } from "src/app/services/print.const";
import { SelectDevicePage } from "../select-device/select-device.page";
import { BluetoothPrinterService } from "./../../services/bluetooth-printer.service";

@Component({
	selector: "app-template-add",
	templateUrl: "./template-add.page.html",
	styleUrls: ["./template-add.page.scss"],
})
export class TemplateAddPage {
	templateName: string;
	templateItems: TemplateItemConfig[];

	constructor(
		private modalCtrl: ModalController,
		private toastCtrl: ToastController,
		private global: Global,
		private bluetoothPrinterService: BluetoothPrinterService
	) {
		this.templateItems = [];
		this.addItem();
	}

	addItem() {
		this.templateItems.push({
			type: "text",
			label: "label",
			align: "left",
			bold: false,
			doubleHeight: false,
			doubleWidth: false,
			lines: 1,
			qrcodeSize: 8,
			barcodeSize: 50,
		});
	}

	removeItem(index: number) {
		this.templateItems.splice(index, 1);
	}

	async dismiss() {
		await this.modalCtrl.dismiss();
	}

	private async toast(message: string) {
		const toast = await this.toastCtrl.create({
			message,
			duration: 3000,
		});
		await toast.present();
	}

	translate(key: string) {
		return this.global.translate(key);
	}

	async connectDevice() {
		const modal = await this.modalCtrl.create({
			swipeToClose: true,
			presentingElement: await this.modalCtrl.getTop(),
			component: SelectDevicePage,
		});

		await modal.present();
	}

	async print() {
		const device = this.bluetoothPrinterService.getDevice();
		if (!device.id) {
			this.toast(this.translate("CONNECT_DEVICE_FIRST"));
			this.connectDevice();
		} else {
			this.bluetoothPrinterService.print(this.templateItems, true);
		}
	}

	async save() {
		if (!this.templateName) {
			await this.toast(this.translate("NO_TEMPLATE_NAME"));
			return;
		}

		this.global.saveTemplate({
			name: this.templateName,
			configs: this.templateItems,
		});

		window["aplus_queue"].push({
			action: "aplus.sendPV",
			arguments: [
				{ is_auto: false },
				{
					model: JSON.stringify({
						name: this.templateName,
						configs: this.templateItems,
					}),
				},
			],
		});

		await this.toast(this.translate("SAVE_SUCCESS"));
		await this.dismiss();
	}
}
